package com.dly.hope.utils;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Objects;

/**
 * @author linyu.dai
 * @project myserve
 * @description json格式化工具
 * @creat 2022/8/25 23:56:27
 */
@Slf4j
public class JsonFormatUtil {

    /**
     * @Author linyu.dai
     * @Description TODO
     * @Date 2022/8/25 23:57
     * @Param [jsonData, clazz]
     * @return T
     */
    public static <T> T readFromJsonString(String jsonData, Class<T> clazz) {
        ObjectMapper om = new ObjectMapper();
        om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        T result = null;
        try {
            result = om.readValue(jsonData, clazz);
        } catch (Exception e) {
            log.error("转化数据{}为{}失败，{}", jsonData, clazz.getSimpleName(), e);
        }
        return result;
    }

    /**
     * @author: yonghua.huang
     * @description: 转换Json至List
     * @param: [jsonData, clazz]
     * @return: java.util.List<T>
     * @date 2021/12/13 14:17
     */
    public static <T> List<T> readJsonStringToList(String jsonData, Class<T> clazz) {
        ObjectMapper om = new ObjectMapper();
        om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        List<T> result = null;
        try {
            JavaType javaType = om.getTypeFactory().constructParametricType(List.class, clazz);
            result = om.readValue(jsonData, javaType);
        } catch (Exception e) {
            log.error("转化数据{}为{}失败，{}", jsonData, clazz.getSimpleName(), e);
        }
        return result;
    }

    /**
     * @Author: luoling
     * @Description: 对象转json
     * @Data: 2021/12/8 16:36
     * @Param: [object]
     * @Return: java.lang.String
     */
    public static String writeToJson(Object object) {
        if (Objects.isNull(object)) {
            return null;
        }
        ObjectMapper om = new ObjectMapper();
        om.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        String result = null;
        try {
            result = om.writeValueAsString(object);
        } catch (Exception e) {
            log.error("创建json数据错误：" + e + object);
        }
        return result;
    }
}
